package com.chase.flashcleaner.activities.main

import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import com.chase.flashcleaner.R
import com.chase.flashcleaner.data.cleanPaths
import com.chase.flashcleaner.initFiles
import com.chase.flashcleaner.utils.*
import java.io.File
import java.math.RoundingMode
import java.text.DecimalFormat

class MainActivity : AppCompatActivity() {

    private lateinit var cpClean: View
    private lateinit var cpProgressBar: View

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        cpClean = findViewById(R.id.view_main_clean)
        cpProgressBar = findViewById(R.id.progress_bar_main_cleaning)

        PermissionUtils.verifyStoragePermissions(this)

        initFiles()

        initCPClean()
    }

    private fun initCPClean() {


        cpClean.setOnClickListener {
            cpProgressBar.visibility = View.VISIBLE
            CleanTask().execute()
        }
    }
    inner class CleanTask:AsyncTask<String, Int, MutableList<FileDeleteInfo>>() {
        override fun doInBackground(vararg params: String?): MutableList<FileDeleteInfo> {
            val deleteInfoList = ArrayList<FileDeleteInfo>()
            cleanPaths.forEachIndexed { index, cleanPath ->
                var fileDeleteInfo = FileDeleteInfo(-2, 0.0)
                if (cleanPath.necessary) {
                    fileDeleteInfo = deleteDirectory(File(cleanPath.path))
                }
                Log.d("GSCGSC", cleanPath.toString())
                deleteInfoList.add(fileDeleteInfo)
            }
            deleteInfoList.forEach { logd("cnt:${it.cnt}-sizeKB:${it.sizeKB}", "CleanTask.doInBackground") }
            return deleteInfoList
        }

        override fun onPostExecute(result: MutableList<FileDeleteInfo>?) {
            cpProgressBar.visibility = View.GONE
            var deleteCnt = 0
            var sizeKB = 0.0
            result?.forEach {
                if(it.cnt > 0) {
                    deleteCnt += it.cnt
                    sizeKB += it.sizeKB
                }
            }

            val format = DecimalFormat("0.##")
            //未保留小数的舍弃规则，RoundingMode.FLOOR表示直接舍弃。
            format.roundingMode = RoundingMode.FLOOR
            if (sizeKB > M) {
                showToast("清理 $deleteCnt 个文件，共计 ${format.format(sizeKB / M)} G")
            } else if (sizeKB > K) {
                showToast("清理 $deleteCnt 个文件，共计 ${format.format(sizeKB / K)} M")
            } else {
                showToast("清理 $deleteCnt 个文件，共计 ${format.format(sizeKB)} K")

            }
        }
    }
}
